<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="dishName">
        <el-input
          v-model="queryParams.dishName"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option-group
            v-for="parentCategory in categoryOptions"
            :key="parentCategory.categoryId"
            :label="parentCategory.categoryName"
          >
            <el-option
              v-for="item in parentCategory.children"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-option-group>
          <el-option
            v-for="item in categoryOptions.filter(c => !c.parentCategoryId)"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_dish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="制作部门" prop="departmentId">
        <el-select v-model="queryParams.departmentId" placeholder="请选择制作部门" clearable>
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.departmentId"
            :label="dept.departmentName"
            :value="dept.departmentId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:dish:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:dish:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:dish:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:dish:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="菜品名称" align="center" prop="dishName" />
      <el-table-column label="分类" align="center" min-width="120">
        <template slot-scope="scope">
          <span>
            {{ scope.row.parentCategoryName ?
              `${scope.row.parentCategoryName} / ${scope.row.categoryName}` :
              scope.row.categoryName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span :class="getStatusClass(scope.row.status)">{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制作部门" align="center" prop="departmentName" />
      <el-table-column label="图片路径" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:dish:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:dish:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option-group
              v-for="parentCategory in categoryOptions"
              :key="parentCategory.categoryId"
              :label="parentCategory.categoryName"
            >
              <el-option
                v-for="item in parentCategory.children"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-option-group>
            <el-option
              v-for="item in categoryOptions.filter(c => !c.parentCategoryId)"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.sys_dish_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="制作部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择制作部门">
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.departmentId"
              :label="dept.departmentName"
              :value="dept.departmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图片路径" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDish, getDish, delDish, addDish, updateDish } from "@/api/manage/dish";
import { listCategory } from "@/api/manage/category";  // 使用现有的列表接口
import { listDepartment } from "@/api/manage/department";  // 使用现有的列表接口

export default {
  name: "Dish",
  dicts: ['sys_dish_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品管理表格数据
      dishList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dishName: null,
        categoryId: null,
        status: null,
        departmentId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dishName: [
          { required: true, message: "菜品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        departmentId: [
          { required: true, message: "制作部门不能为空", trigger: "blur" }
        ],
      },
      // 分类选项列表
      categoryOptions: [],
      // 部门选项列表
      departmentOptions: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询菜品管理列表 */
    getList() {
      this.loading = true;
      listDish(this.queryParams).then(response => {
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dishId: null,
        dishName: null,
        categoryId: null,
        price: null,
        status: null,
        departmentId: null,
        image: null,
        description: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dishId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 获取分类和部门数据 */
    async getOptions() {
      try {
        // 使用现有的列表接口，设置较大的pageSize
        const [categoryRes, deptRes] = await Promise.all([
          listCategory({ pageSize: 999 }),
          listDepartment({ pageSize: 999 })
        ]);

        // 处理返回的数据
        this.categoryOptions = this.handleTree(categoryRes.rows, "categoryId", "parentId");
        this.departmentOptions = deptRes.rows;
      } catch (error) {
        console.error("获取选项数据失败", error);
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getOptions();
      this.open = true;
      this.title = "添加菜品";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await this.getOptions();
      const dishId = row.dishId || this.ids;
      getDish(dishId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dishId != null) {
            updateDish(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDish(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dishIds = row.dishId || this.ids;
      this.$modal.confirm('是否确认删除菜品管理编号为"' + dishIds + '"的数据项？').then(function() {
        return delDish(dishIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/dish/export', {
        ...this.queryParams
      }, `dish_${new Date().getTime()}.xlsx`)
    },
    /** 获取状态样式类名 */
    getStatusClass(status) {
      const statusMap = {
        '0': 'status-stop',
        '1': 'status-start'
      }
      return statusMap[status] || ''
    },
    /** 获取状态文字 */
    getStatusText(status) {
      const statusMap = {
        '0': '停售',
        '1': '起售'
      }
      return statusMap[status] || status
    }
  }
};
</script>

<style scoped>
.status-stop {
  background-color: #F56C6C;
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
.status-start {
  background-color: #67C23A;
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>
